package querysrc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.subway.babynote.syncdata.ClientDataRecord;
import com.subway.babynote.syncdata.StringUtil;

import serverdata.ServerDataRecord;

public abstract class query_hwuser extends query {
	String sqlscript_insert="";
	String sqlscript_select_ts = "";

	public query_hwuser(sqlConnectionHandler sqlconhandler) {
		super(sqlconhandler);
		// TODO Auto-generated constructor stub
	}
	
	public int InserthwRecord(List<ClientDataRecord.hwUserRecord> records, int user_id)
	{
		querydb qdb = null;
		Connection con = null;
		
		try
		{
			boolean bret = true;
			con = this.init();	
			int iret = -1;
			int count = 0;
			int maxts = 0;
			if(bret)
			{
				maxts = this.getMaxts(con,user_id);
			}
			if(!this.needInsert(records, maxts))
			{
				iret = 0;
				return iret;
			}
			if(bret)
			{
				con.setAutoCommit(false);
				qdb = new querydb(con,this.sqlscript_insert);			
				bret = qdb.prePS();
			}
			if(bret)
			{
				Iterator<ClientDataRecord.hwUserRecord> it = records.iterator();
				while(it.hasNext())
				{
					ClientDataRecord.hwUserRecord fr = it.next();
					if(fr.ts > maxts)
					{
						this.setPSparam(qdb.ps, fr, user_id);
						iret = qdb.execPSInsert();
						count++;
					}
				}
				con.commit();				
			}			
			return count;
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		finally
		{
			this.release_querydb(qdb);
			this.release_connection(con);
			this.finalize();
		}
	}
	
	private boolean needInsert(List<ClientDataRecord.hwUserRecord> records, int maxts)
	{
		Iterator<ClientDataRecord.hwUserRecord> it = records.iterator();
		while(it.hasNext())
		{
			ClientDataRecord.hwUserRecord fr = it.next();
			if(fr.ts > maxts)
				return true;			
		}
		return false;
	}
	
	private int getMaxts(Connection con,int user_id)
	{
		return this.getMaxts_base(con, user_id, this.sqlscript_select_ts,
				sqlscripts.sql_hw_max_ts_select_c1);
	}
	
	private int setPSparam(PreparedStatement ps, ClientDataRecord.hwUserRecord fr, int user_id)
	{		
		try
		{
			ps.setInt(1, user_id);
			ps.setFloat(2,fr.value);
			ps.setInt(3, fr.ts);			
			return 0;
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
	}

}
